package com.starhub.application.collection.client;

import com.starhub.application.collection.common.TableCreationHelper;
import com.starhub.application.collection.annotation.CollectionClient;
import com.starhub.application.collection.common.EmbeddingHelper;
import com.starhub.application.collection.common.MilvusCreationHelper;
import com.starhub.application.collection.dto.DataDefinitionDto;
import com.starhub.application.collection.dto.DataManipulationDto;
import com.starhub.application.collection.entity.KnowledgeCollection;
import com.starhub.application.collection.entity.MetaDataEntity;
import com.starhub.application.collection.enums.CollectionTypeEnums;
import com.starhub.application.collection.enums.MetaDataCollectionTypeEnums;
import com.starhub.application.collection.mapper.MetaDataMapper;
import com.starhub.engine.generator.genid.IdGenerator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 元数据表客户端实现
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-06
 */
@Slf4j
@Component
@CollectionClient(CollectionTypeEnums.META_DATA)
public class MetaDataClient implements CollectionClientInterface {
    
    @Autowired
    private MilvusCreationHelper milvusCreationHelper;
    
    @Autowired
    private TableCreationHelper tableCreationHelper;
    
    @Autowired
    private EmbeddingHelper embeddingHelper;
    
    @Autowired
    private MetaDataMapper metaDataMapper;
    
    @Override
    public boolean createCollection(DataDefinitionDto collection) {
        MetaDataCollectionTypeEnums metaDataCollectionTypeEnums = MetaDataCollectionTypeEnums.getByCode(collection.getMetaStorageType());
        switch (metaDataCollectionTypeEnums) {
            case DATABASE_REPRESENTATION:
                return createDataBaseCollection(collection);
            case VECTOR_REPRESENTATION:
                return createVectorCollection(collection);
            default:
                throw new IllegalArgumentException("Invalid meta storage type: " + collection.getMetaStorageType());
        }
    }
    
    /**
     * 添加字段
     * @param collection 知识库表信息
     * @return 是否添加成功
     */
    @Override
    public boolean addFields(DataDefinitionDto collection) {
        // TODO: 实现主数据表的添加字段逻辑
        return true;
    }

    /**
     * 删除知识库表
     * @param collection 知识库表信息
     * @return 是否删除成功
     */
    @Override
    public boolean deleteCollection(DataDefinitionDto collection) {
        // TODO: 实现元数据表的删除逻辑
        return true;
    }

    /**
     * 保存数据
     * @param dataManipulationDto 数据操作DTO
     * @return 数据ID
     */
    @Override
    public String saveData(DataManipulationDto dataManipulationDto) {
        KnowledgeCollection knowledgeCollection = dataManipulationDto.getKnowledgeCollection();
        MetaDataCollectionTypeEnums metaDataCollectionTypeEnums = MetaDataCollectionTypeEnums.getByCode(knowledgeCollection.getMetaStorageType());
        switch (metaDataCollectionTypeEnums) {
            case DATABASE_REPRESENTATION:
                return saveDataBaseData(dataManipulationDto);
            case VECTOR_REPRESENTATION:
                return saveVectorData(dataManipulationDto);
            default:
                throw new IllegalArgumentException("Invalid meta storage type: " + dataManipulationDto.getItemId() + " " + dataManipulationDto.getKnowledgeCollection().getMetaStorageType());
        }
    }

    /**
     * 更新数据
     * @param dataManipulationDto 数据操作DTO
     * @return 数据ID
     */
    @Override
    public boolean updateData(DataManipulationDto dataManipulationDto) { 
        KnowledgeCollection knowledgeCollection = dataManipulationDto.getKnowledgeCollection();
        MetaDataCollectionTypeEnums metaDataCollectionTypeEnums = MetaDataCollectionTypeEnums.getByCode(knowledgeCollection.getMetaStorageType());
        switch (metaDataCollectionTypeEnums) {
            case DATABASE_REPRESENTATION:
                return updateDataBaseData(dataManipulationDto);
            case VECTOR_REPRESENTATION:
                return updateVectorData(dataManipulationDto);
            default:
                throw new IllegalArgumentException("Invalid meta storage type: " + dataManipulationDto.getItemId() + " " + dataManipulationDto.getKnowledgeCollection().getMetaStorageType());
        }
    }

    /**
     * 删除数据
     * @param dataManipulationDto 数据操作DTO
     * @return 是否删除成功
     */
    @Override
    public boolean deleteData(DataManipulationDto dataManipulationDto) {
        KnowledgeCollection knowledgeCollection = dataManipulationDto.getKnowledgeCollection();
        MetaDataCollectionTypeEnums metaDataCollectionTypeEnums = MetaDataCollectionTypeEnums.getByCode(knowledgeCollection.getMetaStorageType());
        switch (metaDataCollectionTypeEnums) {
            case DATABASE_REPRESENTATION:
                return deleteDataBaseData(dataManipulationDto);
            case VECTOR_REPRESENTATION:
                return deleteVectorData(dataManipulationDto);
            default:
                throw new IllegalArgumentException("Invalid meta storage type: " + dataManipulationDto.getItemId() + " " + dataManipulationDto.getKnowledgeCollection().getMetaStorageType());
        }
    }

    /**
     * 创建数据库表示的元数据表
     * @param collection 知识库表信息
     * @return 是否创建成功
     */
    private boolean createDataBaseCollection(DataDefinitionDto collection) {
        try {
            // 检查表是否已存在
            if (tableCreationHelper.isTableExists(collection.getCollectionIdentifier())) {
                log.warn("Table already exists: {}", collection.getCollectionIdentifier());
                return false;
            }

            // 创建基础元数据表
            boolean success = tableCreationHelper.createBaseMetaTable(collection.getName(), collection.getCollectionIdentifier());
            return success;
        } catch (Exception e) {
            log.error("Failed to create database collection: {}", collection.getCollectionIdentifier(), e);
            throw new RuntimeException("Failed to create database collection: " + e.getMessage(), e);
        }
    }

    /**
     * 创建向量表示的元数据表
     * @param collection 知识库表信息
     * @return 是否创建成功
     */
    private boolean createVectorCollection(DataDefinitionDto collection) {
        try {
            milvusCreationHelper.createDefaultCollection(collection);
        } catch (Exception e) {
            throw new RuntimeException("创建Milvus集合失败: " + e.getMessage(), e);
        }
        return true;
    }

    /**
     * 保存数据库表示的元数据表
     * @param dataManipulationDto
     * @return
     */
    private String saveDataBaseData(DataManipulationDto dataManipulationDto) {
        try {
            String tableName = TableCreationHelper.getTableName(dataManipulationDto.getKnowledgeCollection().getCollectionIdentifier());

            // 执行插入操作
            String id = IdGenerator.generateIdStr();
            // 构建实体对象
            MetaDataEntity entity = new MetaDataEntity();
            entity.setId(id);
            entity.setItemId(id); // 使用生成的id作为itemId
            entity.setContent(dataManipulationDto.getContent());
            entity.setBaseId(dataManipulationDto.getBaseId());
            entity.setCollectionId(dataManipulationDto.getCollectionId());

            // 使用Mapper插入数据
            int result = metaDataMapper.insertIntoTable(tableName, entity);
            if (result <= 0) {
                throw new RuntimeException("保存数据失败");
            }

            // 返回插入的ID
            return id;
        } catch (Exception e) {
            log.error("保存数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("保存数据失败: " + e.getMessage());
        }
    }

    /**
     * 保存数据
     * @param dataManipulationDto
     * @return
     */
    private String saveVectorData(DataManipulationDto dataManipulationDto) {
        embeddingHelper.embeddingData(dataManipulationDto);
        return dataManipulationDto.getItemId();
    }

    /**
     * 更新数据库表示的元数据表
     * @param dataManipulationDto
     * @return
     */
    private boolean updateDataBaseData(DataManipulationDto dataManipulationDto) {
        try {
            String tableName = TableCreationHelper.getTableName(dataManipulationDto.getKnowledgeCollection().getCollectionIdentifier());

            // 使用Mapper更新数据
            int result = metaDataMapper.updateContentByItemId(
                tableName,
                dataManipulationDto.getItemId(),
                dataManipulationDto.getContent()
            );
            
            if (result <= 0) {
                throw new RuntimeException("更新数据失败");
            }
            return true;
        } catch (Exception e) {
            log.error("更新数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新向量数据
     * @param dataManipulationDto
     * @return
     */
    private boolean updateVectorData(DataManipulationDto dataManipulationDto) {
        return embeddingHelper.embeddingUpdateData(dataManipulationDto);
    }
    
    /**
     * 删除数据库数据
     * @param dataManipulationDto
     * @return
     */
    private boolean deleteDataBaseData(DataManipulationDto dataManipulationDto) {
        try {
            String tableName = TableCreationHelper.getTableName(dataManipulationDto.getKnowledgeCollection().getCollectionIdentifier());

            // 使用Mapper删除数据
            metaDataMapper.deleteByItemId(
                tableName,
                dataManipulationDto.getItemId()
            );
            
            return true;
        } catch (Exception e) {
            log.error("删除数据失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除数据失败: " + e.getMessage());
        }
    }

    /**
     * 删除向量数据
     * @param dataManipulationDto
     * @return
     */
    private boolean deleteVectorData(DataManipulationDto dataManipulationDto) {
        return embeddingHelper.embeddingDeleteData(dataManipulationDto);
    }
} 
